//
//  GFTbView.m
//  Qyer
//
//  Created by dlios on 15/10/21.
//  Copyright (c) 2015年 GF. All rights reserved.
//

#import "GFTbView.h"

@implementation GFTbView
- (instancetype)initWithFrame:(CGRect)frame{
    _temp = 0;
    self = [super initWithFrame:frame];
    if (self) {
        _tableArray = [NSMutableArray array];
        _table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 124 * HEIGHT) style:UITableViewStyleGrouped];
        [_table setDelegate:self];
        [_table setDataSource:self];
        [_table setBounces:YES];
        [self addSubview:_table];  
        [self getAfnString];
        [_table addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(addHeader)];
        [_table addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(addFooter)];
    }
    return self;
}

- (void)addHeader{
    [_tableArray removeAllObjects];
    [self getAfnString];
}
- (void)addFooter{
//    [_tableArray removeAllObjects];
    ++_temp;
    [self getAfnString];
}
- (void)getAfnString{
    [AFN getdataWithString:[NSString stringWithFormat:@"http://chanyouji.com/api/trips/featured.json?page=%ld", _temp] block:^(id block) {
        for (NSDictionary *dic in block) {
            GFTbModel *model = [GFTbModel modelWithDictionary:dic];
            [_tableArray addObject:model];
        }
        [_table reloadData];
        [_table.header endRefreshing];
        [_table.footer endRefreshing];
    } BLOCK:^(id BLOCK) {
        
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _tableArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 230 * HEIGHT;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *guoFeng = @"cell";
    GFTbTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:guoFeng];
    if (!cell) {
        cell = [[GFTbTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:guoFeng];
    }
    GFTbModel *model = [_tableArray objectAtIndex:indexPath.row];
    [cell getTableModel:model];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *preString = @"http://chanyouji.com/api/trips/";
    NSString *hasString = @".json";
    GFTbModel *model = [_tableArray objectAtIndex:indexPath.row];
    NSString *comString = [NSString stringWithFormat:@"%@%@%@", preString, model.cId, hasString];
    [self.tbDelegate getAfnString:comString imageString:model.front_cover_photo_url dictionary:model.user];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
